/**
 * www.easyplatform.cn ©2016
 */
package cn.easyplatform.studio.utils;

import cn.easyplatform.studio.web.editors.support.CodeFormatter;
import org.apache.commons.codec.binary.Base64;

import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.security.SecureRandom;

/**
 * @author <a href="mailto:shiny_vc@163.com">陈云亮</a> <br/>
 * @since 2.0.0 <br/>
 */
public class SecurityUtils {

	public final static String getSalt() {
		try {
			SecureRandom sr = SecureRandom.getInstance("SHA1PRNG", "SUN");
			byte[] salt = new byte[16];
			sr.nextBytes(salt);
			return salt.toString();
		} catch (Exception e) {
		}
		return null;
	}

	public final static String getSecurePassword(String passwordToHash,
			String salt) {
		String generatedPassword = null;
		try {
			MessageDigest md = MessageDigest.getInstance("SHA-256");
			md.update(salt.getBytes());
			byte[] bytes = md.digest(passwordToHash.getBytes());
			StringBuilder sb = new StringBuilder();
			for (int i = 0; i < bytes.length; i++) {
				sb.append(Integer.toString((bytes[i] & 0xff) + 0x100, 16)
						.substring(1));
			}
			generatedPassword = sb.toString();
		} catch (NoSuchAlgorithmException e) {
		}
		return generatedPassword;
	}

	public final static String encodeBizPassword(String password) {
		try {
			MessageDigest digest = MessageDigest.getInstance("SHA-256");
			byte[] hashed = digest.digest(password.getBytes());
			for (int i = 0; i < 1023; i++) {
				digest.reset();
				hashed = digest.digest(hashed);
			}
			return Base64.encodeBase64String(hashed);
		} catch (Exception ex) {
			return password;
		}
	}

	public static void main(String[] args) {
		String str = "#db.update('test');";
		System.out.println(CodeFormatter.formatJS(str));
	}
}
